'use strict';

import React from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '@material-ui/core/styles'
import {
  Dialog,
  AppBar,
  Toolbar,
  IconButton,
  Typography,
  Button,
} from '@material-ui/core'
import CloseIcon from '@material-ui/icons/Close'

import PatientBlock from './patient'
import DiagnosisBlock from '../diagnosisdesk/diagnosis'
import config from '../../../controller/config'

const electron = window.require('electron')

const styles = theme => ({
  root: {
    padding: 16
  },
  appBar: {
    position: 'relative',
  },
  flex: {
    flex: 1,
  },
  iframe: {
    height: '100%'
  }
});

class CheckDesk extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      _id: 'history',
      dialog: false,
      ID: ''
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps._id !== undefined) {
      this.setState({ _id: nextProps._id })
    }
  }

  componentDidMount() {
    electron.ipcRenderer.on('saved', (e, arg) => {
      this.setState({
        dialog: true,
        ID: arg.prescription.ID,
        patient: arg.patient
      })
    })
  }

  handlePullMedicines(d) {
    let states = {
      rows: d.length,
    }
    const keys = [
      'drug',
      'dose',
      'doseunit',
      'usage',
      'times',
      'days',
      'count',
      'postfix',
      'price',
      'comment'
    ]
    for (let k = 0; k < d.length; k += 1) {
      let drug = d[k].drug
      if (drug === undefined) continue
      drug.value = drug._id
      drug.label = `${drug.name}<${drug.specs}>`
      states[`drug_${k}`] = d[k].drug
      states[`dose_${k}`] = d[k].dose
      states[`doseunit_${k}`] = d[k].doseunit
      states[`usage_${k}`] = {label: d[k].usage, value: d[k].usage}
      states[`times_${k}`] = {label: d[k].times, value: d[k].times}
      states[`days_${k}`] = d[k].days
      states[`count_${k}`] = d[k].count
      states[`postfix_${k}`] = d[k].postfix
      states[`price_${k}`] = d[k].price
      states[`comment_${k}`] = d[k].comment
    }
    electron.ipcRenderer.send('patient', {
      _id: 'history',
      medicines: states
    })
    this.diagnosisBlock.fetch('history')
  }
  
  render() {
    const { classes } = this.props
    return (
      <div className={classes.root}>
        <PatientBlock
          _id={this.state._id}
          patient={this.state.patient || {}}
          ref={(r) => this.patient_ref = r}
          onPullMedicines={(d) => this.handlePullMedicines(d)}
        />
        <DiagnosisBlock
          medicineRef={(r) => {
            console.log('============', r)
            this.diagnosisBlock = r
          }}
          _id={this.state._id}
        />
        <Dialog
          open={this.state.dialog}
          fullScreen
          onClose={() => this.setState({dialog: false})}
        >
          <AppBar className={classes.appBar}>
            <Toolbar>
              <IconButton color="inherit" onClick={() => this.setState({ dialog: false})} aria-label="Close">
                <CloseIcon />
              </IconButton>
              <Typography variant="h6" color="inherit" className={classes.flex}>
                {this.state.ID}
              </Typography>
              <Button color="inherit" onClick={() => this.handlePrint()}>
                打印
              </Button>
            </Toolbar>
          </AppBar>
          <iframe className={classes.iframe} src={`${config.baseUrl}api/prescription?ID=${this.state.ID}`} />
        </Dialog>
      </div>
    )
  }
}

CheckDesk.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(CheckDesk);